<?php
class Admin extends Admin_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Admin_m');
        $this->_data['sidebar'] = 'admin';
        
    }
    
    function index(){
    	$this->list_admin();	
    }
    
    //--login--//
    function login(){
    	if($this->session->userdata('user_id') && $this->session->userdata('group_id')){
    		redirect(site_url('admin'));
    	}
    	
    	$config = array(
    						array('field' => "email",
    							  'label' => "Email",
    							  'rules' => "required|valid_email"
    							 ),
    							 
    						array('field' => "password",
    							  'label' => "Password",
    							  'rules' => "required"
    							 ),
    		 		   );
    	$this->form_validation->set_rules($config);
    	
    	if($this->input->post('submit')){
    		if($this->form_validation->run() == FALSE){
    			$data['error'] = "error";
                $this->load->view('admin/admin/login', $data);	
    		}else{
    			$password = md5($this->input->post('password'));
    			$email = $this->input->post('email');
    			
    			if($this->Admin_m->login($email, $password) === FALSE){
    				$data['error'] = "error";
                	$this->load->view('admin/admin/login', $data);		
    			}else{
    				redirect(site_url("admin"));
    			}
    		}
    	}else{
    		$this->load->view('admin/admin/login');	
    	}
    	
    	
    }
   
	//--check login--//
	function check_login($str, $collums){
		$parts = explode('.', $collums);
		$count = $this->Admin_m->check_login($parts[0], $str);
		if($count < 0){
			$this->form_validation->set_message("check_login", "Wrong email or password");
			return FALSE;
		}else{
			return TRUE;
		}
	}
		     
    
    //--Logout--//
 	public function logout() {
        $this->Admin_m->logout();
        redirect('admin');
    }
    
    

    //--List all admin--//
    
    function list_admin(){
    is_admin();
    $this->_data['page_title'] = "administrateur liste";
    $per_page = $this->uri->segment(3);
    $off_set = $this->uri->segment(4);
    
    if($per_page == ""){
    	$per_page = 5;
    }
    if($off_set == ""){
    	$off_set = "";
    }
    
    $config['base_url'] = base_url()."index.php/admin/list_admin/".$per_page."/";
    $config['per_page'] = 5;
    $config['uri_segment'] = 4;
    $config['total_rows'] = $this->Admin_m->count_admin();
    if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
    
    $this->_data['admins'] = $this->Admin_m->get_all_admin($per_page, $off_set);
    $this->pagination->initialize($config);
    $this->_data['pagination'] = $this->pagination->create_links();
    $this->_data['total'] = $config['total_rows'];
    $this->_data['perpage'] = $per_page;
    $this->_data['offset'] = $off_set;
    $this->display_admin('admin/admin/list_admin');
    }
    
    
    
    //--Add new admin--//
	
    function add_admin() {
    	is_admin();
    	$this->_data['page_title'] = "Ajouter administrateur";
    	
    	//--validate config--//
    	
    	$config = array(
    						array('field' => 'first_name', 
    							  'label' => lang('first_name'), 
    							  'rules' => 'required|xss_clean'),
    						
    						array('field' => 'last_name', 
    							  'label' => lang('last_name'), 
    							  'rules' => 'required|xss_clean'),
    						
    						array('field' => 'display_name', 
    							  'label' => lang('display_name'), 
    							  'rules' => 'required|xss_clean'),
    						
    						array('field' => 'email', 
    							  'label' => lang('email'), 
    							  'rules' => 'required|xss_clean|valid_email|callback_check_exist_email'),
    						
    						array('field' => 'confirm_email', 
    							  'label' => lang('confirm_email'), 
    							  'rules' => 'required|xss_clean|matches[email]'),
    						
    						array('field' => 'password', 
    							  'label' => lang('password'), 
    							  'rules' => 'required|xss_clean|min_length[5]'),
    						
    						array('field' => 'confirm_password', 
    							  'label' => lang('confirm_password'), 
    							  'rules' => 'required|xss_clean|matches[password]'),
    			
    				    );
  		$this->form_validation->set_rules($config);
    	    	
    	if($this->input->post('register')){
    		if($this->form_validation->run() === FALSE){//validate fail
    			$this->display_admin('admin/admin/add_admin');		
    		}else{// validate ok
    			//insert data to users
    			$email = $this->input->post('email');
    			$password = md5($this->input->post('password'));
    			$query_add_admin = $this->Admin_m->add_admin($email, $password);
    			if($query_add_admin){//insert to database success
    				$this->session->set_flashdata('error', lang('add') ." ". lang('success'));
    				redirect(site_url('admin'));
    			}else{// insert fail
    				$this->_data['insert_error'] = "Insert failed!";
    			}
    			
    				
    		}		
    	}else{
    		$this->display_admin('admin/admin/add_admin');	
    	}
    		
    
    }
	
	//--Edit admin profiles--//
	function edit_profile($user_id = null){
		is_admin();
		$this->_data['page_title'] = "Modifier le profil";
		if($this->Admin_m->get_admin_profiles($user_id) === FALSE){
			redirect("admin");
		}
		$admin_data = $this->_data['admin_data'] = $this->Admin_m->get_admin_profiles($user_id);
		$admin_dob = $admin_data->dob;
		
		$config = array(
    						array('field' => 'first_name', 
    							  'label' => lang('first_name'), 
    							  'rules' => 'required|xss_clean'),
    						
    						array('field' => 'last_name', 
    							  'label' => lang('last_name'), 
    							  'rules' => 'required|xss_clean'),
    						
    						array('field' => 'display_name', 
    							  'label' => lang('display_name'), 
    							  'rules' => 'required|xss_clean'),
    						
    						array('field' => 'phone', 
    							  'label' => lang('phone'), 
    							  'rules' => 'xss_clean|min_length[5]|max_length[11]'),
    						
    						array('field' => 'address', 
    							  'label' => lang('address'), 
    							  'rules' => 'xss_clean'),
    						
    						array('field' => 'gender', 
    							  'label' => lang('gender'), 
    							  'rules' => 'xss_clean'),
    						
    						array('field' => 'active', 
    							  'label' => lang('active'), 
    							  'rules' => 'xss_clean')
    						
    						
    				    );
  		$this->form_validation->set_rules($config);
		
		if($this->input->post("edit_profile")){
			if($this->form_validation->run() === FALSE){
				$this->display_admin('admin/admin/edit_profile');	
			}else{
				$d = $this->input->post("birth_date");
				$m = $this->input->post("birth_month");
				$y = $this->input->post("birth_year");
				$birthday = $y."-".$m."-".$d;
				$dob = human_to_unix($birthday);
				$first_name = $this->input->post("first_name");
				$last_name = $this->input->post("last_name");
				$address = $this->input->post("address");
				$display_name = $this->input->post("display_name");
				$gender = $this->input->post("gender");
				$phone = $this->input->post("phone");
				$mobile = $this->input->post("mobile");
				$active = $this->input->post("active");
				
				$data = array("first_name"=>$first_name, 
							  "last_name"=>$last_name, 
							  "dob"=>$dob, 
							  "display_name"=>$display_name, 
							  "address"=>$address, 
							  "mobile_number"=>$mobile, 
							  "telephone_number"=>$phone, 
							  "gender"=>$gender 
							  );
							  
				$data_active = array("active" => $active);
				$query_active = $this->Admin_m->update_admin_active($user_id, $data_active);
				$query = $this->Admin_m->update_admin_profile($user_id, $data);	
				if($query){
					$this->session->set_flashdata('error', lang('edit_profile') . lang('success'));
					redirect(site_url("admin"));	
				}
			}	
		}else{
			$this->display_admin("admin/admin/edit_profile");
		}
	}
    
    //--Check exist email--//
	function check_exist_email($email){
    	$result = $this->Admin_m->get_particular_record('users', 'email', $email);
    	if(count($result) >0){
    		$this->form_validation->set_message('check_exist_email', "L'address E-mail a été utilisé");
    		return FALSE;
    	}else{
    		return TRUE;
    	}	
    }
    
    //--Delete Admin--//
    public function delete_admin($user_id) {
        //is_super_admin();
        /*if ($user_id == 1) {
            redirect('admin');
        }*/
                
        $query = $this->Admin_m->delete_admin($user_id);
        if ($query)
            $this->session->set_flashdata('error', lang('delete') . lang('success'));
        else
            $this->session->set_flashdata('error', lang('delete') . lang('fail'));
        redirect('admin/list_admin');
    }

    function delete_multi_admin() {
        //is_super_admin();
        $list = "";
        $adelete = $this->input->post('delete');
        $N = count($adelete);
        for ($i = 0; $i < $N; $i++) {
            
            if ($adelete[$i] != "")
                $list = $list . ',' . $adelete[$i];
        }
        $list = '(' . substr($list, 1) . ')';

        $query = $this->Admin_m->delete_admins($list);
        if ($query)
            $this->session->set_flashdata('error', lang('delete') . lang('success'));
        else
            $this->session->set_flashdata('error', lang('delete') . lang('fail'));
        redirect('admin/list_admin');
    }
    
    //--change pass--//
	function change_pass() {
        is_admin();
        $this->_data['page_title']="Change Pass";
        $this->session->set_userdata('current_url', current_url());
        $user_id = $this->session->userdata('user_id');
        
        $config = array(
            array(
                'field' => 'apass',
                'label' => lang('old_pass'),
                'rules' => 'required|md5|callback_check_old_password'
            ),
            array(
                'field' => 'npass',
                'label' => lang('new_pass'),
                'rules' => 'required|matches[confirm_npass]|md5'
            ),
            array(
                'field' => 'confirm_npass',
                'label' => lang('conf_pass'),
                'rules' => 'required|md5'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->form_validation->run()) {
            $pass = $this->input->post('apass');
            $query = $this->Admin_m->is_password($pass, $user_id);
            if ($query) {
                $npass = $this->input->post('npass');
                $query1 = $this->Admin_m->change_pass($user_id, $npass);
                if ($query1) {
                    $this->session->set_flashdata('error', lang('change_pass') . ' '.lang('success'));
                    redirect('admin');
                } else {
                    $this->session->set_flashdata('error', lang('change_pass') .' '. lang('fail'));
                    redirect('admin');
                }
                redirect('admin');
            } else {
                $this->_data['error'] = lang('in_pass');
                $this->display_admin('admin/admin/change_pass');
            }
        }else
            $this->display_admin('admin/admin/change_pass');
    }
    
    //--check old password--//
    function check_old_password($password){
    	$count = $this->Admin_m->get_old_password($password);
    	if($count>0){
    		return TRUE;
    	}else{
    		$this->form_validation->set_message("check_old_password", "Ancien mot de passe incorrect");
    		return FALSE;
    	}
    }

	

}

